package com.flutter.flutter_location;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.content.Context;
import android.text.TextUtils;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.LinkedHashMap;
import java.util.Map;
/** FlutterLocationPlugin */
public class FlutterLocationPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;

  static public LocationManager locationManager;
  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutter_location");
    channel.setMethodCallHandler(this);
    locationManager = (LocationManager)flutterPluginBinding.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
  }

  // This static function is optional and equivalent to onAttachedToEngine. It supports the old
  // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
  // plugin registration via this function while apps migrate to use the new Android APIs
  // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
  //
  // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
  // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
  // depending on the user's project. onAttachedToEngine or registerWith must both be defined
  // in the same class.
  public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_location");
    channel.setMethodCallHandler(new FlutterLocationPlugin());



    locationManager = (LocationManager)registrar.activeContext().getSystemService(Context.LOCATION_SERVICE);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } if (call.method.equals("getLocation")) {
      onLocation(call,result);
    }
    else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

  public  void onLocation(@NonNull MethodCall call, @NonNull Result result) {
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
      Location location = locationManager
              .getLastKnownLocation(LocationManager.GPS_PROVIDER);
      if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Map<String, Object> info = new LinkedHashMap<String, Object>();
        info.put("callbackTime", formatUTC(System.currentTimeMillis(), null));
        info.put("latitude",latitude);
        info.put("longitude",longitude);
        result.success(info);
      }
    }
  }

  public static String formatUTC(long time, String strPattern) {
    if (TextUtils.isEmpty(strPattern)) {
      strPattern = "yyyy-MM-dd HH:mm:ss";
    }
    SimpleDateFormat sdf = null;
    try {
      sdf = new SimpleDateFormat(strPattern, Locale.CHINA);
      sdf.applyPattern(strPattern);
    } catch (Throwable e) {
    }
    return sdf == null ? "NULL" : sdf.format(time);
  }
}
